package com.cet.algorithm.双指针法;

/**
 * @program: algorithm
 * @description: 替换空格
 * @author: 陈恩涛
 * @create: 2022-03-24 11:05
 **/
public class ReplaceSpace {

    /**
     * 简单解法
     * @param s
     * @return
     */
    public String replaceSpace(String s) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                result.append("%20");
            } else {
                result.append(s.charAt(i));
            }
        }
        return result.toString();
    }

    /**
     * 双指针法
     * @param s
     * @return
     */
    public String replaceSpace2(String s) {
        StringBuilder sb = new StringBuilder();
        // 扩充空间
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                sb.append("  ");
            }
        }
        int left = s.length() - 1;
        s += sb.toString();
        int right = s.length() - 1;
        char[] ca = s.toCharArray();
        while (left >= 0) {
            if (ca[left] == ' ') {
                ca[right--] = '0';
                ca[right--] = '2';
                ca[right--] = '%';
                left--;
            } else {
                ca[right--] = ca[left--];
            }
        }
        return new String(ca);
    }


    public static void main(String[] args) {
        System.out.println(new ReplaceSpace().replaceSpace2(" abc ad "));
    }
}
